#使用requests实现有道翻译信息爬取

import requests
import json
import time,random
import hashlib

def getMD5(value):
    #创建MD5对象
    md5 = hashlib.md5()
    #对指定的字符串进行加密
    md5.update(bytes(value,encoding='utf-8'))
    #拿出加密后的内容,并赋值给sign
    sign = md5.hexdigest()
    return sign

def Mytranslate(keyword):
    url = 'http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule'

    salt = int(time.time() * 1000) + random.randint(0, 10)
    sign = "fanyideskweb"+keyword+str(salt)+"ebSeFb%=XZ%T[KZ)c(sy!"

    data = {
        'i':keyword,
        'from':'AUTO',
        'to':'AUTO',
        'smartresult':'dict',
        'client':'fanyideskweb',
        'salt':salt,
        'sign':getMD5(sign),
        'doctype':'json',
        'version':'2.1',
        'keyfrom':'fanyi.web',
        'action':'FY_BY_REALTIME',
        'typoResult':'false',
        }
    headers = {
        'Accept':'application/json, text/javascript, */*; q=0.01',
        'Accept-Encoding':'deflate',
        'Accept-Language':'zh-CN,zh;q=0.9',
        'Connection':'keep-alive',
        'Content-Length':str(len(data)),
        'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8',
        'Cookie':'OUTFOX_SEARCH_USER_ID=-1398774374@10.169.0.83; JSESSIONID=aaaleqa4r3nGe9nUsL3Ew; OUTFOX_SEARCH_USER_ID_NCOO=1539705759.0456028; ___rl__test__cookies=1544973325362',
        'Host':'fanyi.youdao.com',
        'Origin':'http://fanyi.youdao.com',
        'Referer':'http://fanyi.youdao.com/',
        'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36',
        'X-Requested-With':'XMLHttpRequest',
        }
 
    res = requests.post(url,data=data,headers=headers)
    str_json = res.content.decode('utf-8')
    myjson = json.loads(str_json)
    info = myjson['smartResult']['entries'][1]
    print(info)


if __name__ == '__main__':
    while True:
        keyword = input('请输入要翻译的内容:')
        if keyword == 'q':
            break;
        Mytranslate(keyword)
